
const dynamicId = "analyze";

// 在扩展安装/更新时创建菜单（确保只创建一次）
chrome.runtime.onInstalled.addListener(() => {
  // 先移除可能存在的旧菜单项
  chrome.contextMenus.remove(dynamicId, () => {
    // 忽略"菜单不存在"的错误
    if (chrome.runtime.lastError) {
      console.log('移除旧菜单时:', chrome.runtime.lastError);
    }
    
    // 创建新菜单项
    chrome.contextMenus.create({
      id: dynamicId,
      title: "解析byRP",
      contexts: ["page"]
    }, () => {
      if (chrome.runtime.lastError) {
        console.error('菜单创建失败:', chrome.runtime.lastError);
      }
    });
  });
});



chrome.contextMenus.onClicked.addListener(async (clickData) => {
  if (clickData.menuItemId === dynamicId ) {
    try {
      // 获取当前标签页
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      
      // 执行内容脚本
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ["js/hide.js"]
      });

      // 读取存储配置
      const { default_api, default_open } = await chrome.storage.sync.get([
        "default_api",
        "default_open"
      ]);

      // 设置默认值
      let openType = default_open ?? "0";
      if (!default_open) {
        await chrome.storage.sync.set({ default_open: "0" });
      }

      // 处理API配置
      if (!default_api) {
        try {
          const response = await fetch(chrome.runtime.getURL("json/api.json"));
          const jsonApi = await response.json();
          const targetApi = jsonApi[0];
          await chrome.storage.sync.set({ default_api: targetApi });
          const targetUrl = openType === "0" 
          ? targetApi.url + clickData.pageUrl 
          : chrome.runtime.getURL("html/options.html");
          chrome.tabs.create({ url: targetUrl });
              
        } catch (error) {
          console.error("API加载失败:", error);
        }
      } else {
        openType === "0"
        ? chrome.tabs.create({ url: default_api.url + clickData.pageUrl })
        : chrome.tabs.create({
              url: chrome.runtime.getURL("html/options.html"),
        });
        
        // 存储临时URL
        await chrome.storage.sync.set({ temp_url: clickData.pageUrl });
      
      }
    } catch (error) {
      console.error("运行时错误:", error);
    }
  }
});